import PropTypes from "prop-types";
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { Dialog, ErrorBlock } from "antd-mobile";
import { BARCODE_PARSER } from "@common/constants";
import ItemBlk from "./ItemBlk";
import { createAction, callNativeApi } from "@common/utils";
import { SET_SCAN_DATA } from "@store/global-state/action-types";
import {
  SAGA_STOCKTAKING_LOAD_ITEM_LIST,
  SAGA_STOCKTAKING_DEL_ITEM_BY_ID,
} from "@store/stocktaking/saga-types";
import {
  UPDATE_STOCKTAKING_ITEM,
  ADD_STOCKTAKING_ITEM,
  UPDATE_STOCKTAKING_ITEM_REAL_QTY,
  CLEAR_STOCKTAKING_ITEM_LIST,
} from "@store/stocktaking/action-types";

const ItemInfo = () => {
  const location = useLocation();
  const { pathname } = location;
  const searchParams = new URLSearchParams(location.search);
  const dispatch = useDispatch();
  const itemList = useSelector((state) => state.stocktaking.itemList);
  const scandata = useSelector((state) => state.globalState.scandata);

  useEffect(() => {
    dispatch(
      createAction(SAGA_STOCKTAKING_LOAD_ITEM_LIST, {
        orderId: searchParams.get("id"),
        locationId: searchParams.get("locationId"),
      })
    );

    return () => {
      dispatch(createAction(SET_SCAN_DATA, null));
      dispatch(createAction(CLEAR_STOCKTAKING_ITEM_LIST));
    };
  }, []);

  const setItemFields = (parseResult) => {
    let { id, itemCode, itemName, realQty } = parseResult;
    let itemIdx = itemList.findIndex((i) => i.itemCode === itemCode);
    if (itemIdx !== -1) {
      dispatch(
        createAction(UPDATE_STOCKTAKING_ITEM, {
          id,
          itemCode,
          itemName,
          realQty,
        })
      );
      setTimeout(() => {
        document.getElementById(id).scrollIntoView();
      }, 200);
    } else {
      if (pathname.includes("open")) {
        Dialog.confirm({
          content: "当前单据不包含所扫物料, 是否添加?",
          onConfirm: () => {
            dispatch(
              createAction(ADD_STOCKTAKING_ITEM, {
                id,
                itemCode,
                itemName,
                realQty,
              })
            );
            setTimeout(() => {
              document.getElementById(id).scrollIntoView();
            }, 200);
          },
          onCancel: () => {
            dispatch(createAction(SAGA_STOCKTAKING_DEL_ITEM_BY_ID, { id }));
          },
        });
      } else {
        dispatch(
          createAction(ADD_STOCKTAKING_ITEM, {
            id,
            itemCode,
            itemName,
            realQty,
          })
        );
        setTimeout(() => {
          document.getElementById(id).scrollIntoView();
        }, 200);
      }
    }
  };

  useEffect(() => {
    if (scandata) {
      callNativeApi({
        classFullName: BARCODE_PARSER,
        action: "parse",
        params: {
          orderId: searchParams.get("id"),
          locationId: searchParams.get("locationId"),
          barcode: scandata,
          bizType: "STOCKTAKING",
        },
        needNonce: false,
      })
        .then((resp) => {
          let result = resp.data ? resp.data.payload : resp.payload;
          setItemFields(result);
          dispatch(createAction(SET_SCAN_DATA, null));
          return;
        })
        .catch((error) => console.log(error));
    }
  }, [scandata]);

  const handleValChange = (id, realQty) => {
    dispatch(
      createAction(UPDATE_STOCKTAKING_ITEM_REAL_QTY, {
        id,
        realQty,
      })
    );
  };

  return (
    <>
      {itemList?.length > 0 ? (
        itemList.map((record, idx) => (
          <ItemBlk
            key={idx}
            type={pathname.includes("blind") ? "BLIND" : "OPEN"}
            data={record}
            handleValChange={handleValChange}
          />
        ))
      ) : (
        <ErrorBlock status="empty" description="请扫码添加数据" title="" />
      )}
    </>
  );
};

ItemInfo.propTypes = {
  type: PropTypes.string,
};

export default ItemInfo;
